<?php
include_once dirname(__FILE__).'/excelFormat.php';
include_once dirname(__FILE__).'/../../db/db.php';
include_once dirname(__FILE__).'/../AttributesName.php';
include_once dirname(__FILE__).'/../../utils/download.php';

include_once dirname(__FILE__).'/../../../Classes/PHPExcel.php';
include_once dirname(__FILE__).'/../../../Classes/PHPExcel/Writer/Excel2007.php';

/* 取得传过来的属性 */
$formatArray = excelFormat($_POST['type']);
$formatIndex = formatIndex();
$queryStr = $_POST['query'];
$fileName = $_POST['fileName'];

/* 创建一个Excel */
$objPHPExcel = new PHPExcel();
/* 保存到2007格式 */
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);

/* 设置Excel属性 */
$objPHPExcel->getProperties()->setCreator();     // 创建人
$objPHPExcel->getProperties()->setLastModifiedBy();  // 最后修改人
$objPHPExcel->getProperties()->setTitle();           // 标题
$objPHPExcel->getProperties()->setSubject();     // 题目
$objPHPExcel->getProperties()->setDescription();         // 描述
$objPHPExcel->getProperties()->setKeywords();            // 关键字
$objPHPExcel->getProperties()->setCategory();            // 种类

/* 设置当前的sheet */
$objPHPExcel->setActiveSheetIndex(0);
$objActSheet = $objPHPExcel->getActiveSheet();          // 当前活动的Sheet
$objActSheet->setTitle('sheet');  // sheet的name

/* 设置宽度 */
//$objActSheet->getColumnDimension('A')->setWidth(20);

/* 设置单元格的值 */
$startColumn = 1;
for($i=0; $i<count($formatArray); $i++){
    $objActSheet->setCellValue($formatIndex[$i].$startColumn, $formatArray[$i]);
}
$n = $startColumn+1;        // 数据起始行
$dataArray = null;

/* 从数据库循环读出 */
$query = mysql_query($queryStr, $GLOBALS['DB']);
$attributesName = null;
switch ($_POST['type']) {
    case 'Awards':
        $attributesName = AttributesName::$awards;
        break;
    case 'Treaties':
        $attributesName = AttributesName::$treaties;
        break;
    default:
        break;
}
while( $rs = mysql_fetch_array($query)){
    $array = null;
    foreach ($attributesName as $value) {
        if($value=='auditingState'){
            if($rs[$value]==0){
                $array[] = '未审核';
            }else{
                $array[] = '已审核';
            }
        }else{
            $array[] = $rs[$value];
        }
    }
    for($i=0; $i<count($formatArray); $i++){
        $dataArray[$formatIndex[$i].$n]=$array[$i];
    }
    $n++;
}
foreach ($dataArray as $key => $value) {
    $objActSheet->setCellValue($key, $value);
}

/* 输出内容 */
if($fileName==null || $fileName==""){
    $fileName = 'DefaultFile';
}
$outputFileName = dirname(__FILE__).'/../../../temp/'.$fileName.'.xlsx';
$objWriter->save(iconv("utf-8", "gbk",$outputFileName));

/* 下载文件 */
downloadFile($outputFileName);
